package com.ysynzehao.handler;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * niuzehao
 * 2018/12/10 16:53.
 */
@Component
@Aspect
@Slf4j
public class ControllerLogAspect {

    @Pointcut("execution(public * com.ysynzehao.controller.*.*(..))")
    public void logAspect() {
    }

    @Before("logAspect()")
    public void before(JoinPoint joinPoint) {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 记录下请求内容
        log.info("request_url : " + request.getRequestURL().toString());
        log.info("request_method : " + request.getMethod());
        log.info("request_ip : " + request.getRemoteAddr());
        log.info("class_method : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("params : " + Arrays.toString(joinPoint.getArgs()));
    }

    @AfterThrowing(throwing = "throwable", pointcut = "logAspect()")
    public void afterException(Throwable throwable) {
        log.error("error :" + throwable.getMessage(), throwable);
    }

    @AfterReturning(returning = "obj", pointcut = "logAspect()")
    public void afterReturning(Object obj) {
        // 处理完请求，返回内容
        log.info("return : " + obj);
    }

    @Around("logAspect()")
    public Object invoke(ProceedingJoinPoint point) {
        Object object = null;
        try {
            object = point.proceed();
            object = ResponseEntity.ok("success:" + object);
        } catch (Throwable e) {
            log.error("", e);
            object = ResponseEntity.ok("fail" + object);
        }
        return object;
    }

}
